package com.yuji.aacar.controller.fragment.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.yuji.aacar.R;
import com.yuji.aacar.base.BaseFragment;
import com.yuji.aacar.base.EventConst;
import com.yuji.aacar.base.UserCenter;
import com.yuji.aacar.bean.beans.OrderList;
import com.yuji.aacar.bean.response.LoginResponse;
import com.yuji.aacar.bean.response.OrderListResponse;
import com.yuji.aacar.bean.response.VersionResponse;
import com.yuji.aacar.controller.adapter.OrderHomeAdapter;
import com.yuji.aacar.controller.adapter.RecyclerViewItemTouchListener;
import com.yuji.aacar.controller.message.MessageActivity;
import com.yuji.aacar.controller.order.WriteOrderActivity;
import com.yuji.aacar.controller.order.detail.OrderDetailActivity;
import com.yuji.aacar.core.cores.event.CoreEventBusMessage;
import com.yuji.aacar.core.cores.event.CoreEventCenter;
import com.yuji.aacar.core.cores.services.CoreServiceResponse;
import com.yuji.aacar.service.BaseServiceMediator;
import com.yuji.aacar.service.BaseServiceParams;
import com.yuji.aacar.widgets.autolayout.AutoRelativeLayout;
import com.yuji.aacar.widgets.dialogue.VersionDialog;
import com.yuji.aacar.widgets.pulltorefresh.PtrFrameLayout;
import com.yuji.aacar.widgets.pulltorefresh.core.PtrDefaultHandler2;
import com.yuji.aacar.widgets.pulltorefresh.core.WptrClassicFrameLayout;
import com.yuji.aacar.widgets.textview.PingFangTextView;
import com.yuji.aacar.wxapi.WXPayEntryActivity;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.yuji.aacar.R.id.back_image;

/**
 * <li>Package:com.yuji.aacar.controller.fragments.mine</li>
 * <li>Author: lining </li>
 * <li>Date: 2018/2/28</li>
 * <li>Description:   </li>
 */

public class OrderFragment extends BaseFragment {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(back_image)
    AutoRelativeLayout backImage;
    @BindView(R.id.title_content)
    PingFangTextView titleContent;
    @BindView(R.id.back_login)
    PingFangTextView backLogin;
    @BindView(R.id.title_message_iv)
    ImageView titleMessageIv;
    @BindView(R.id.title_message_rl)
    AutoRelativeLayout titleMessageRl;
    @BindView(R.id.title_rl)
    AutoRelativeLayout titleRl;
    @BindView(R.id.layout_recyclerview)
    RecyclerView layoutRecyclerview;
    @BindView(R.id.layout_pull_to_refresh)
    WptrClassicFrameLayout layoutPullToRefresh;
    @BindView(R.id.no_order_layout1)
    ImageView noOrderLayout1;
    @BindView(R.id.no_order_layout2)
    PingFangTextView noOrderLayout2;
    @BindView(R.id.no_order_layout3)
    PingFangTextView noOrderLayout3;
    @BindView(R.id.no_order_layout)
    AutoRelativeLayout noOrderLayout;

    private ArrayList<OrderList> mDatas;
    OrderHomeAdapter adapter;

    private int pageNumber = 0;
    private int pageSize = 10000;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void showFragemt() {
        super.showFragemt();
    }

    @Override
    public void alreadyBindBaseViewModel() {
        super.alreadyBindBaseViewModel();

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            resetMessageStatus();
            requestOrderList();
        }
    }

    private void resetMessageStatus() {
        LoginResponse user = UserCenter.getCurrentUser();
        if (null != user){
            String has = UserCenter.getNewMessage(user.getMemberId());
            if (has.contentEquals("1")){
                titleMessageIv.setImageResource(R.mipmap.message_new_normal);
            } else {
                titleMessageIv.setImageResource(R.mipmap.message_no_normal);
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.ptr_list_view_, null);
        ButterKnife.bind(this, rootView);
        super.onCreateView(inflater, container, savedInstanceState);
        titleContent.setText("我的订单");
        titleBack.setVisibility(View.GONE);
        titleMessageRl.setVisibility(View.VISIBLE);
        titleMessageRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presentControllerFromFragment(MessageActivity.class);
                LoginResponse user = UserCenter.getCurrentUser();
                if (null != user){
                    UserCenter.setNewMessage(user.getMemberId(),"0");
                    CoreEventCenter.postMessage(EventConst.PUSH_MESSAGE_CHECKED, "xiaoxi");
                }
            }
        });
        layoutPullToRefresh.setPullToRefresh(true);
        //阻力系数，阻力越大，能拉动范围越小，默认为1.7f
        layoutPullToRefresh.setResistance(1.7f);
        //系数越大，需拉动越大的距离才能刷新或加载，默认1.2f
        layoutPullToRefresh.setRatioOfHeaderHeightToRefresh(1.2f);

        layoutPullToRefresh.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                layoutPullToRefresh.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        layoutPullToRefresh.refreshComplete();
                    }
                }, 2000);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {

                pageNumber = 0;
                requestOrderList();
            }
        });
        layoutPullToRefresh.setMode(PtrFrameLayout.Mode.BOTH);


        adapter = new OrderHomeAdapter(this.getActivity(), mDatas);

        layoutRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        //        layoutRecyclerview.addItemDecoration(new RecycleViewDivider(
        //                getActivity(), LinearLayoutManager.VERTICAL, 20, getResources().getColor(R.color.listitembackground)));
        layoutRecyclerview.setAdapter(adapter);
        layoutRecyclerview.addOnItemTouchListener(new RecyclerViewItemTouchListener(layoutRecyclerview, new RecyclerViewItemTouchListener.OnItemClickListener() {

            @Override
            public void onItemClick(View view) {

                OrderHomeAdapter.ViewHolder holder = (OrderHomeAdapter.ViewHolder) layoutRecyclerview.getChildViewHolder(view);
//                String orderNumber = holder.getOrderNumber().getText().toString();
//                String washType = holder.getOrderList().getWashType();
//                String status = holder.getOrderList().getOrderStatus();
//                String amount = holder.getOrderList().getOrderAmount();

//                Intent intent = getActivity().getIntent();
//                intent.putExtra("orderNo", orderNumber);
//                intent.putExtra("washType", washType);

//                if (status.contentEquals(Const.ORDER_STATUS_SHOULD_PAY)) {//待支付
//
//                    intent.putExtra("orderNumber", orderNumber);
//                    intent.putExtra("amount", amount);
//                    presentControllerFromFragment(WXPayEntryActivity.class, intent);
//
//                } else if (status.contentEquals(ORDER_STATUS_SHOULD_CONFIRM)) {//待接单
//
//                    DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                        }
//                    };
//                    showAlertSingleButtonDialogue(getActivity(), "已经收到", "我们会尽快与您联系", "我知道了", clickListener);
//                }

//                holder.getLayout().setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//
//                        presentControllerFromFragment(OrderDetailActivity.class, intent);
//                    }
//                });
//
//                holder.getPay().setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        intent.putExtra("orderNumber", orderNumber);
//                        intent.putExtra("amount", amount);
//
//                        presentControllerFromFragment(WXPayEntryActivity.class, intent);
//
//                    }
//                });

//                holder.getCancel().setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                cancelOrder(orderNumber);
//                            }
//                        };
//                        showAlertDialogue(getActivity(), "取消", "确定取消订单？", "确定", clickListener);
//                    }
//                });

                //                int position = layoutRecyclerview.getChildViewHolder(view).getPosition();
                //                //                LogUtil.e("position--", position);
                //                //                Room roomTemp = datas.get(position);
            }

            @Override
            public void onItemLongClick(View view) {

            }
        }));
        return rootView;
    }

    private void requestOrderList() {
        requestParams = BaseServiceParams.list(pageNumber + "", pageSize + "");
        doTask(BaseServiceMediator.LIST);
    }


    @Override
    public void requestSuccess(CoreServiceResponse response) {
        super.requestSuccess(response);
        if (response.getRequestCode() == BaseServiceMediator.LIST_CODE) {
            OrderListResponse submitResponse = (OrderListResponse) response.getResponse();
            mDatas = submitResponse.getResultList();
            adapter.updateData(mDatas);
            int currentPageNumber = submitResponse.getPage().getPageNumber();
            int currentPageSize = submitResponse.getPage().getPageSize();
            int currentTotalPage = submitResponse.getPage().getTotalPage();
            layoutPullToRefresh.refreshComplete();
            if (null != mDatas && mDatas.size() > 0) {
                noOrderLayout.setVisibility(View.GONE);
                layoutPullToRefresh.setVisibility(View.VISIBLE);

            } else {
                noOrderLayout.setVisibility(View.VISIBLE);
                layoutPullToRefresh.setVisibility(View.GONE);
            }
        }
    }

    @OnClick({R.id.no_order_layout1, R.id.no_order_layout2, R.id.no_order_layout3, R.id.no_order_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.no_order_layout1:
                requestOrderList();
                break;
            case R.id.no_order_layout2:
                requestOrderList();
                break;
            case R.id.no_order_layout3:
                requestOrderList();
                break;
            case R.id.no_order_layout:
                requestOrderList();
                break;
        }
    }

    @Override
    public void handleMessage(CoreEventBusMessage message) {
        super.handleMessage(message);
        if (message.getMessageCode().contentEquals(String.valueOf(EventConst.ORDER_ITEM))) {
            Intent intent = (Intent) message.getMessageObjects();
            presentControllerFromFragment(OrderDetailActivity.class, intent);
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.ORDER_PAY))) {
            Intent intent = (Intent) message.getMessageObjects();
            presentControllerFromFragment(WXPayEntryActivity.class, intent);
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.VERSION_UPDATE))) {
            if (!isHidden()){
                VersionResponse intent = (VersionResponse) message.getMessageObjects();
                if (intent.getFlag().contentEquals("1")) {
                    VersionDialog dialog = new VersionDialog(getActivity(), intent);
                    if (!dialog.isShowing()) {
                        dialog.showDialog();
                    }
                }
            }
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.PUSH_MESSAGE))) {
            if (!isHidden()){
                titleMessageIv.setImageResource(R.mipmap.message_new_normal);
            }
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.PUSH_MESSAGE_CHECKED))) {
            if (!isHidden()){
                titleMessageIv.setImageResource(R.mipmap.message_no_normal);
            }
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.BACK_FROM_ORDER_DETAIL))) {
            requestOrderList();
        } else if(message.getMessageCode().contentEquals(String.valueOf(EventConst.ORDER_BUY_AGAIN))){
            Intent intent = (Intent) message.getMessageObjects();
            presentControllerFromFragment(WriteOrderActivity.class, intent);
        }
    }
}
